package com.cn.wanxi.dao.impl;

import com.cn.wanxi.dao.NavDao;
import com.cn.wanxi.dto.CompanyModelDto;
import com.cn.wanxi.dto.NavModelDto;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.util.JDBC;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 1.封装sql语句
 * 2.执行JDBC代码
 */
public class NavImpl implements NavDao {
    @Override
    public int add(NavModelDto navModelDto) {
        String sql = "INSERT INTO `nav_one` " +
                "(`href`, `title`) VALUES " +
                "('" + navModelDto.getHref() + "', '" + navModelDto.getTitle() + "');";

        return JDBC.excuteUpdate(sql);
    }

    @Override
    public List<NavModel> getNavModelList() {
        String sql = "select * from nav_one where status=1";//封装sql语句
        ResultSet resultSet = JDBC.getResultSet(sql);//执行sql语句，返回结果集
        List<NavModel> list = new ArrayList<>();
        try {
            while (resultSet.next()) {
                NavModel navModel = new NavModel();
                navModel.setId(resultSet.getInt("id"));
                navModel.setHref(resultSet.getString("href"));
                navModel.setTitle(resultSet.getString("title"));
                navModel.setStatus(resultSet.getInt("status"));
                list.add(navModel);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBC.close();
        }
        return list;
    }

    /**
     * 数据实现层
     * 1.封装sql语句
     * 2.执行JDBC
     *
     * @param navModel
     * @return
     */
    @Override
    public int del(NavModel navModel) {
        String sql = "delete from nav_one where id=" + navModel.getId();
        return JDBC.excuteUpdate(sql);
    }

    @Override
    public NavModel findById(int id) {
        String sql = "select * from nav_one where id=" + id;
        ResultSet resultSet = JDBC.getResultSet(sql);//执行sql语句，返回结果集
        NavModel navModel = new NavModel();
        try {
            while (resultSet.next()) {
                navModel.setId(resultSet.getInt("id"));
                navModel.setHref(resultSet.getString("href"));
                navModel.setTitle(resultSet.getString("title"));
                navModel.setStatus(resultSet.getInt("status"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return navModel;
    }

    @Override
    public int update(NavModel navModel) {
        String sql = "update nav_one set " +
                "href='" + navModel.getHref() + "'," +
                "title='" + navModel.getTitle() + "'," +
                "status=" + navModel.getStatus() + " where id=" + navModel.getId();
//        String ss = "UPDATE `nav_one` SET `href` = '" + navModel.getHref() + "', " +
//                "`title` = '" + navModel.getTitle() + "', " +
//                "`status` = '" + navModel.getStatus() + "' WHERE (`id` = '" + navModel.getId() + "');\n";
        return JDBC.excuteUpdate(sql);
    }
}
